// pages/search/search.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";

const app = getApp();

let isIphoneX = app.globalData.isIphoneX;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 输入框内容
    isIphoneX: isIphoneX,
    value:'',
    userId:2,  
    parentId:0,
    timeSlot:0,
    fileType:0,
    searchlist:'',
    tupianlist:'',
    wenjianlist:'',
    // 最近浏览和筛选
    shaixuan:0,
    start:'',
    end:'',
    idzhi:'',
    namezhi:'',

    fileFormat: "",
    filename:"",
    // 三个点弹框   重命名   删除
    showsantc:'',
    showupnametc:'',
    showdeltc:'',
    ischangyong: '',
    isxingbiao: '',
    // 阴影和下拉
    xialashow:-1,
    timename:'按时间段',
    timelist:[
      { name: '全部'},
      { name: '今天'},
      { name: '最近3天'},
      { name: '最近7天'},
      { name: '最近30天'}
    ],
    typename: '按类型',
    typelist:[
      { name: '全部'},
      { name: '文档'},
      { name: '图片'},
      { name: '其他文件'}
    ],
    // 暂无内容
    znawushow:0,
    currentuuid:""

  },

  copy: function (e) {

    var that = this;
    wx.setClipboardData({
      data: that.data.currentuuid,
      success: function (res) {
        that.ylquxiao()
      }
    });
  },


    // 预览框隐藏
    ylquxiao() {
      this.setData({
        shownotyulantc: false,
        currentuuid:''
      })
    },

  inputfocus:function(){
    // this.data.tupianlist= []
    // this.data.wenjianlist = []


    this.setData({
      tupianlist:[],
      wenjianlist :[]
    })
  },
  // 获取最近浏览 图片
  gettupian() {
    ajax('/applet/viewPicture', {
      data: {
        userId: this.data.userId,
        parentId: this.data.parentId,
        timeSlot: this.data.timeSlot,
        orderType: 2,
        page: 1,
        size: 100,
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {
      console.log('获取图片成功')

      for (var a in res.data.list) {
        res.data.list[a].choose = 0     // 0未选中  1选中
      }
      // var tupianlist = res.data.list

      console.log('获取文件成功')
      res.data.list.forEach((valve, index) => {

        if (valve.fileType == 0) {

          valve.fileFormat = valve.fileName
          valve.firstname = valve.fileName
        } else {

          let fileName = valve.fileName.lastIndexOf(".");//取到文件名开始到最后一个点的长度
          let fileNameLength = valve.fileName.length;//取到文件名长度
          let fileFormat = valve.fileName.substring(fileName + 1, fileNameLength);//截
          let firstname = valve.fileName.substring(0, fileName);//截
          valve.fileFormat = fileFormat
          valve.firstname = firstname
        }
      })
      for (var a in res.data.list) {
        res.data.list[a].choose = 0     // 0未选中  1选中
      }

      var tupianlist = res.data.list
      this.setData({
        tupianlist: tupianlist
      })
    })
  },
  // 获取最近浏览 文件
  getwenjian() {
    ajax('/applet/viewFile', {
      data: {
        userId: this.data.userId,
        parentId: this.data.parentId,
        timeSlot: this.data.timeSlot,
        orderType: 2,
        page: 1,
        size: 100,
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {
      console.log('获取文件成功')

      for (var a in res.data.list) {
        res.data.list[a].choose = 0     // 0未选中  1选中
      }
      // var tupianlist = res.data.list

      console.log('获取文件成功')
      res.data.list.forEach((valve, index) => {

        if (valve.fileType == 0) {

          valve.fileFormat = valve.fileName
          valve.firstname = valve.fileName
        } else {

          let fileName = valve.fileName.lastIndexOf(".");//取到文件名开始到最后一个点的长度
          let fileNameLength = valve.fileName.length;//取到文件名长度
          let fileFormat = valve.fileName.substring(fileName + 1, fileNameLength);//截
          let firstname = valve.fileName.substring(0, fileName);//截
          valve.fileFormat = fileFormat
          valve.firstname = firstname
        }
      })
      for (var a in res.data.list) {
        res.data.list[a].choose = 0     // 0未选中  1选中
      }

      var wenjianlist = res.data.list

      this.setData({
        wenjianlist: wenjianlist
      })
    })
  },

  delnamezhi() {
    this.setData({
      namezhi: ''
    })
  },
  // bindtouchstart：触屏开始时间
  // bindtouchend ：触屏结束时间
  // bindlongtap：绑定长按事件
  // catchtap：单击事件
  mytouchstart: function (e) {  //记录触屏开始时间
    this.setData({ start: e.timeStamp })
  },
  mytouchend: function (e) {  //记录触屏结束时间
    this.setData({ end: e.timeStamp })
  },
  deleteitem: function (e) {  //长按事件内容
    console.log('长按事件内容')
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var ischangyong = e.currentTarget.dataset.ischangyong;
    var isxingbiao = e.currentTarget.dataset.isxingbiao

    var fileFormat = e.currentTarget.dataset.fileformat
    var filename = e.currentTarget.dataset.filename

    this.setData({
      idzhi: id,
      namezhi: name,
      ischangyong: ischangyong,
      isxingbiao: isxingbiao,
      showsantc: true,

      fileFormat: fileFormat,
      filename: filename
    })
  },
  onLinkDatail: function (e) {   //单击事件内容
    if (this.data.end - this.data.start < 350) {
      console.log('单击事件内容')
      console.log(e)
      var current = e.target.dataset.src;
      var index = e.currentTarget.dataset.ind;
      var imglist = []
      this.data.tupianlist.forEach((value, index) => {
        imglist.push(value.previewUrl)
      })
      var newlist = []
      for (var i = index; i < imglist.length; i++) {
        newlist.push(imglist[i])
      }
      for (var i = 0; i < index; i++) {
        newlist.push(imglist[i])
      }
      wx.previewImage({
        current: current, // 当前显示图片的http链接 
        urls: newlist // 需要预览的图片http链接列表 
      })
    }
  },
  // 跳转图片页
  totupage: function () {
    wx.navigateTo({
      url: '/pages/tupage/tupage?thismuluid= -1'
    })
  },

  settime(id) {
    ajax('/applet/updateTime', {
      data: {
        id: id
      },
      header: {
        "Accept": "application/json" // 默认值
      },
      method: "post",
    }, res => {
      console.log(res.data.list)
      if (res.msg == "SUCCESS") {

      }
    })
  },
  // 跳转文件页
  totowenjian: function (e) {
    
    var id = e.currentTarget.dataset.id
    var type = e.currentTarget.dataset.type
    var muluname = e.currentTarget.dataset.muluname

    var src = e.currentTarget.dataset.src
    var preview = e.currentTarget.dataset.preview
    var uuid = e.currentTarget.dataset.uuid


    src = encodeURIComponent(src)

    if (type == 0) {
      wx.navigateTo({
        url: '/pages/towenjian/towenjian?thismuluid=' + id + '&muluname=' + muluname,
      })
    } else {
      if (preview == 1) {
        // wx.navigateTo({
        //   url: '/pages/details/details?src=' + src
        // })

        var huancun = wx.getStorageSync('huancun')

        if (huancun == '') {
          huancun = []
          wx.downloadFile({
            // 示例 url，并非真实存在
            url: decodeURIComponent(src),
            success: function (res) {
              console.log("aaa:" + "666a");
              const filePath = res.tempFilePath


              var item = {
                id: id,
                tempFilePath: filePath
              }
              huancun.push(item)

              wx.setStorageSync('huancun', huancun)

              wx.openDocument({
                filePath: filePath,
                success: function (res) {
                  console.log('打开文档成功')
                }
              })
            }
          })
        } else {

          var flage = -1
          for (var i = 0; i < huancun.length; i++) {
            if (huancun[i].id == id) {
              flage = i
            }
          }

          if (flage != -1) {
            wx.openDocument({
              filePath: huancun[flage].tempFilePath,
              success: function (res) {
                console.log('打开文档成功')
              }
            })
          } else {
            wx.downloadFile({
              // 示例 url，并非真实存在
              url: decodeURIComponent(src),
              success: function (res) {
                console.log("aaa:" + "666a");
                const filePath = res.tempFilePath


                var item = {
                  id: id,
                  tempFilePath: filePath
                }
                huancun.push(item)

                wx.setStorageSync('huancun', huancun)

                wx.openDocument({
                  filePath: filePath,
                  success: function (res) {
                    console.log('打开文档成功')
                  }
                })
              }
            })
          }
        }

        this.settime(id)
      } else {
        this.setData({
          currentuuid: uuid
        })
        // wx.showToast({
        //   title: '该文件不可预览！',
        //   icon: 'none',
        //   duration: 2000
        // })

        this.setData({
          shownotyulantc: true
        })
      }
    }
  },
  // 三个点显示
  sanxianshi(e) {
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var ischangyong = e.currentTarget.dataset.ischangyong;
    var isxingbiao = e.currentTarget.dataset.isxingbiao;


    var fileFormat = e.currentTarget.dataset.fileformat

    var filename = e.currentTarget.dataset.filename

    console.log(isxingbiao, 'isxingbiao')
    this.setData({
      idzhi: id,
      namezhi: name,
      ischangyong: ischangyong,
      isxingbiao: isxingbiao,
      showsantc: true,
      fileFormat: fileFormat,
      filename: filename
    })
  },
  // 三个点隐藏
  sanquxiao() {
    this.setData({
      showsantc: false
    })
  },
  // 三个点设为常用
  swcy() {
    var isCommonly;
    if (this.data.ischangyong == 0) {
      isCommonly = 1
    } else {
      isCommonly = 0
    }
    ajax('/applet/appletRename', {
      data: {
        id: this.data.idzhi,
        isCommonly: isCommonly        // 1为常用 0为非常用
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {
      console.log('设为常用成功')
      this.setData({
        showsantc: false
      })
      if (this.data.shaixuan == 0) {
        this.gettupian()
        this.getwenjian()
      } else {
        this.search()
      }
    })
  },
  // 三个点设为星标
  swxb() {
    var isxingbiao;
    if (this.data.isxingbiao == 0) {
      isxingbiao = 1
    } else {
      isxingbiao = 0
    }
    ajax('/applet/appletRename', {
      data: {
        id: this.data.idzhi,
        isFollow: isxingbiao        // 1为星标 0为非星标
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {
      console.log('设为星标成功')
      this.setData({
        showsantc: false
      })
      if (this.data.shaixuan == 0) {
        this.gettupian()
        this.getwenjian()
      } else {
        this.search()
      }
    })
  },
  // 重命名显示
  swcmm() {
    this.setData({
      showsantc: false,
      showupnametc: true
    })
  },
  // 重命名的值
  getnamezhi(e) {
    this.setData({
      namezhi: e.detail.value
    })
  },
  // 重命名隐藏
  cmmquxiao() {
    this.setData({
      showupnametc: false
    })
  },
  // 重命名确认ajax
  cmmqqueren() {

    if (this.data.namezhi == '') {
      wx.showToast({
        title: '名称不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (this.data.filename == this.data.fileFormat) {
      var pinname = this.data.namezhi
    } else {
      var pinname = this.data.namezhi + '.' + this.data.fileFormat
    }

    ajax('/applet/appletRename', {
      data: {
        id: this.data.idzhi,
        fileName: pinname
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {
      console.log('重命名成功')
      this.setData({
        showupnametc: false
      })
      if (this.data.shaixuan == 0) {
        this.gettupian()
        this.getwenjian()
      } else {
        this.search()
      }
    })
  },
  // 单个分享
  swfx() {
    wx.navigateTo({
      url: '/pages/fenxiang/fenxiang?idlist=' + [this.data.idzhi],
    })

  },
  // 删除框显示
  swsc() {
    this.setData({
      showsantc: false,
      showdeltc: true
    })
  },
  // 删除框隐藏
  scquxiao() {
    this.setData({
      showdeltc: false
    })
  },
  // 删除框确认ajax
  scqueren() {
    ajax('/applet/appletRename', {
      data: {
        id: this.data.idzhi,
        isDelete: 1         // 1为删除 0为不删除
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {
      console.log('删除成功')
      this.setData({
        showdeltc: false
      })
      if (this.data.shaixuan == 0) {
        this.gettupian()
        this.getwenjian()
      } else {
        this.search()
      }
      
    })
  },
  // 获取搜索的value
  inputvalue: function(e){
    this.setData({
      value: e.detail.value,
    });
  },
  // 搜索列表
  search: function(){
    ajax('/applet/appletSearch', {
      data: {
        userId: this.data.userId,
        parentId: this.data.parentId,
        timeSlot: this.data.timeSlot,
        fileName: this.data.value,
        fileType: this.data.fileType,
        page: 1,
        size: 100,
      },
      header: {
        "Accept": "application/json"
      },
      method: "post",
    }, res => {

      for (var a in res.data.list) {
        res.data.list[a].choose = 0     // 0未选中  1选中
      }
      // var tupianlist = res.data.list

      console.log('获取文件成功')
      res.data.list.forEach((valve, index) => {

        if (valve.fileType == 0) {

          valve.fileFormat = valve.fileName
          valve.firstname = valve.fileName
        } else {

          let fileName = valve.fileName.lastIndexOf(".");//取到文件名开始到最后一个点的长度
          let fileNameLength = valve.fileName.length;//取到文件名长度
          let fileFormat = valve.fileName.substring(fileName + 1, fileNameLength);//截
          let firstname = valve.fileName.substring(0, fileName);//截
          valve.fileFormat = fileFormat
          valve.firstname = firstname
        }
      })
      for (var a in res.data.list) {
        res.data.list[a].choose = 0     // 0未选中  1选中
      }


      var tuarr=[]
      var wenarr=[]
      for (var a in res.data.list){
        if(res.data.list[a].fileType==2){
          tuarr.push(res.data.list[a])
        }else{
          wenarr.push(res.data.list[a])
        }
      }
      console.log(tuarr,'tuarr')
      console.log(wenarr, 'wenarr')
      var searchlist = res.data.list




      if (searchlist.length == 0){
        this.setData({
          shaixuan: 1,
          znawushow: 1,
          tupianlist: tuarr,
          wenjianlist: wenarr
        })
      }else{
        this.setData({
          shaixuan: 1,
          znawushow: 0,
          tupianlist: tuarr,
          wenjianlist: wenarr
        })
      }
    })
  },

  dianjiyinying1:function(){
    this.setData({
      xialashow:-1
    })
  },

  // 按时间段
  timedown:function(){
    this.setData({
      xialashow:0
    })
  },
  timeselect:function(e){
    var idx = e.currentTarget.dataset.index;
    var name = e.currentTarget.dataset.name;
    if (name == "全部") {
      this.setData({
        xialashow: -1,
        timeSlot: idx,
        timename: '按时间段'
      })
    }else{
      this.setData({
        xialashow: -1,
        timeSlot: idx,
        timename: name
      })
    }
    this.search()
  },
  // 按类型
  typedown: function(){
    this.setData({
      xialashow:1
    })
  },
  typeselect:function(e){
    var idx = e.currentTarget.dataset.index;
    var name = e.currentTarget.dataset.name;
    if(name == "全部"){
      this.setData({
        xialashow: -1,
        fileType: idx,
        typename: '按类型'
      })
    }else{
      this.setData({
        xialashow: -1,
        fileType: idx,
        typename: name
      })
    }
    this.search()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      parentId: options.thismuluid,
    })
    this.gettupian()
    this.getwenjian()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
   
  }
})